//
//  NetworkTools+OAuth.swift
//  Swift微博
//
//  Created by 陈竹 on 16/2/26.
//  Copyright © 2016年 陈竹. All rights reserved.
//

import Foundation

extension NetworkTools{
    /// 请求登陆页面
    var oauthURL:NSURL{
        let urlString="https://api.weibo.com/oauth2/authorize?client_id=\(Appkey)&redirect_uri=\(AppRedirectUri)"
        return NSURL(string: urlString)!
    }
    
    ///  获取token
    ///
    ///  - parameter code:     授权成功回到code
    ///  - parameter finished: 完成回调
    func loadAccessToken(code:String,finished:([String : AnyObject]?)->()){
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let params=["client_id":Appkey,
            "client_secret":AppSecret,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":AppRedirectUri]
        
        
        request(.POST, URLString: urlString, parametes: params) {[weak self] (result) -> () in
            guard let result=result,
                let access_token=result["access_token"] as? String,
                let uid=result["uid"] as? String else{
                    print("数据格式不对")
                    finished(nil)
                    return
            }
            //根据请求回来的token和uid加载用户数据
            self?.loadUser(access_token, uid: uid, finished: { (userDict) -> () in
                guard var userDict=userDict else{
                    print("用户加载数据错误")
                    finished(nil)
                    return
                }
                //合并字典
                for (k,v) in result{
                    userDict[k]=v
                }
                finished(userDict)
            })
            
        }
        
    }
}
